//
//  XNDLocationManager.m
//  CityBao
//
//  Created by YueWen on 16/9/1.
//  Copyright © 2016年 wangpj. All rights reserved.
//

#import "QDLocationManager.h"
#import <objc/runtime.h>

static NSString * requestAutorBlock;

///
static NSString *const QDLocationManagerDefaultsAddressKey = @"QDLocationManagerDefaultsAddressKey";
static NSString *const QDLocationManagerLongitudeKey = @"QDLocationManagerLongitudeKey";
static NSString *const QDLocationManagerLatitudeKey = @"QDLocationManagerLatitudeKey";



@interface QDLocationManager()<CLLocationManagerDelegate>

@property (nonatomic, copy) UpdateLocationBlock successBlock;
@property (nonatomic, copy) UpdateFailtureBlock failtureBlock;
@property (nonatomic, strong) CLLocationManager * locationManager;

/// 避免多次回调，延迟5s,默认为true
@property (nonatomic, assign)BOOL shouldLocation;

@end

@implementation QDLocationManager

//更新当前的地理位置
-(void)updateLocationComplete:(UpdateLocationBlock)locationCompleteBlock failtureBlock:(UpdateFailtureBlock)failtureBlockHandle
{
    //设置block
    self.successBlock = locationCompleteBlock;
    self.failtureBlock = failtureBlockHandle;
    
    //检测当前状态
    if([CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined){

        [self.locationManager requestWhenInUseAuthorization];return;
    }
    
    if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusRestricted ||
        [CLLocationManager authorizationStatus] == kCLAuthorizationStatusDenied) {
        failtureBlockHandle(@"定位不允许"); return;
    }
    
    [self.locationManager requestLocation];
    
    
}

-(void)dealloc
{
    self.locationManager.delegate = nil;
    NSLog(@"%@ dealloc",NSStringFromClass([self class]));
}

//进行反地理编译
-(void)reverseGeocodeLocation:(CLLocation *)location Complete:(nonnull ReverseGeocodeSuccessBlock)successBlockHandle Failture:(nonnull UpdateFailtureBlock)failtureBlock
{
    CLGeocoder * geocoder = [[CLGeocoder alloc]init];
    
    [geocoder reverseGeocodeLocation:location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        
        if ( error!= nil )
        {
            failtureBlock(error.localizedDescription);return;
        }
        CLPlacemark *placemark = [placemarks ritl_safeObjectAtIndex:0];
        
        NSMutableDictionary *locationDict = [[NSMutableDictionary alloc] init];
        
        [locationDict setObject:placemark.administrativeArea ?: @"" forKey:@"province"];
        
        NSString *currCity = placemark.locality;
        if (!currCity) {
            //四大直辖市的城市信息无法通过locality获得，只能通过获取省份的方法来获得（如果city为空，则可知为直辖市）
            currCity = placemark.administrativeArea;
        }

        [locationDict setObject:currCity ?: @"" forKey:@"city"];
        
        if (placemark.subLocality) {
            
            [locationDict setObject:placemark.subLocality ?: @"" forKey:@"district"];
        }
        
        if (placemark.thoroughfare) {
            
            [locationDict setObject:placemark.thoroughfare ?: @"" forKey:@"thoroughfare"];
        }
        
        [locationDict setObject:placemark.subLocality ?: @"" forKey:@"subLocality"];
        [locationDict setObject:placemark.name ?: @"" forKey:@"name"];
        
        //数据存储
        [[NSUserDefaults standardUserDefaults] setObject:locationDict forKey:QDLocationManagerDefaultsAddressKey];

        NSLog(@"%@",locationDict);
        
        successBlockHandle(currCity,locationDict);
        
    }];
}


-(CLLocationManager *)locationManager
{
    if (!_locationManager) {
        
        _locationManager = [[CLLocationManager alloc]init];
        _locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters;
        _locationManager.delegate = self;
        
        //初始化
        self.shouldLocation = true;
    }
    
    return _locationManager;
}


#pragma mark - <CLLocationManagerDelegate>

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
    if (self.failtureBlock)
        self.failtureBlock(error.localizedDescription);
}

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations
{
    [manager stopUpdatingLocation];//停止定位
    
    
    if(self.successBlock && self.shouldLocation) {
        
        self.shouldLocation = false;
        self.successBlock(locations.lastObject);
    }
    
    //延迟5秒回正
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        self.shouldLocation = true;
    });
    
    
    //进行保存
    [[NSUserDefaults standardUserDefaults] setObject:@(locations.lastObject.coordinate.longitude) forKey:QDLocationManagerLongitudeKey];
    
    [[NSUserDefaults standardUserDefaults] setObject:@(locations.lastObject.coordinate.latitude) forKey:QDLocationManagerLatitudeKey];
    
}


-(void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status
{
    switch (status) {
        case kCLAuthorizationStatusAuthorizedWhenInUse:
        case kCLAuthorizationStatusAuthorizedAlways:
        {
            [manager startUpdatingLocation];
//            [XNDStatisticManager statisticClickWithEventId:@"app_location_allow" Info:nil];

            //获得block
            void(^block)(void) = objc_getAssociatedObject(self, &requestAutorBlock);
            
            if (block != nil)
            {
                //执行
                block();
                
                //remove
//                objc_setAssociatedObject(self, &requestAutorBlock, nil, OBJC_ASSOCIATION_ASSIGN);
            }
            
        }
            break;
        case kCLAuthorizationStatusNotDetermined:
            [manager requestWhenInUseAuthorization];break;
            
        case kCLAuthorizationStatusDenied:
        {
            //执行位置失败的回调
            if (self.forbidLocalHandler) {
                
                self.forbidLocalHandler();
            }
            
        }break;
            
        default:
            break;
    }
}

@end


@implementation QDLocationManager (RITL_ViewController)


- (dispatch_block_t)forbidLocalHandler
{
    return objc_getAssociatedObject(self, _cmd);
}


- (void)setForbidLocalHandler:(dispatch_block_t)forbidLocalHandler
{
    if (forbidLocalHandler == nil) {
        
        return;
    }
    
    objc_setAssociatedObject(self, @selector(forbidLocalHandler), forbidLocalHandler, OBJC_ASSOCIATION_COPY_NONATOMIC);
}



-(void)checkLocationStatusWithViewController:(UIViewController *)viewController title:(NSString *)requestTitle authorizeBlock:(void (^)(void))authorizedBlock
{
    __weak typeof(viewController) weakViewController = viewController;
    
    NSString *localDefaultKey = @"QDlocaltionCcount";
    
    //获取value
    NSNumber *localCount = [[NSUserDefaults standardUserDefaults] valueForKey:localDefaultKey];
    
    //本地存储
    if (localCount == nil) {
        
        //进行存储
        [[NSUserDefaults standardUserDefaults] setObject:@(1) forKey:localDefaultKey];
    }
    
    
    switch ([CLLocationManager authorizationStatus])
    {
            //表示定位允许
        case kCLAuthorizationStatusAuthorizedWhenInUse:
        case kCLAuthorizationStatusAuthorizedAlways:
        {
            //执行回调
            authorizedBlock();
        }
            
            break;
            
            //表示定位不允许,需要弹出Alert
        case kCLAuthorizationStatusNotDetermined:
        {
            objc_setAssociatedObject(self, &requestAutorBlock, authorizedBlock, OBJC_ASSOCIATION_COPY_NONATOMIC);
            
            //请求定位
            [self.locationManager requestWhenInUseAuthorization];
            
        }
            break;
            
        case kCLAuthorizationStatusDenied:
        case kCLAuthorizationStatusRestricted:
        {
            
            //获得数据
            NSNumber *count = [[NSUserDefaults standardUserDefaults] valueForKey:localDefaultKey];
            
            //进行累加
            NSInteger countInter = count.integerValue + 1;
            
            //进行存储
            [[NSUserDefaults standardUserDefaults]setObject:@(countInter) forKey:localDefaultKey];
            
            
            if (count.integerValue == 5) {//如果满五次

                //check requestTitle
                if (requestTitle == nil) {
                    requestTitle = @"请打开系统设置中“隐私→定位服务”，允许“青岛地铁”使用您的位置。";
                }
                
                
                UIAlertController * alertController = [UIAlertController alertControllerWithTitle:requestTitle
                                                                                          message:nil
                                                                                   preferredStyle:UIAlertControllerStyleAlert];
                
                [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {}]];
                
                [alertController addAction:[UIAlertAction actionWithTitle:@"设置" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                    

                    if (@available(iOS 10.0, *)) {
                        [[UIApplication sharedApplication]openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString] options:@{UIApplicationOpenURLOptionUniversalLinksOnly:@(false)} completionHandler:^(BOOL success) {}];
                    } else {
                        // Fallback on earlier versions
                        [[UIApplication sharedApplication]openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
                    }
            }]];
                
                [weakViewController presentViewController:alertController animated:true completion:^{}];

                //进行清理
                [[NSUserDefaults standardUserDefaults] setObject:@(1) forKey:localDefaultKey];
                
            }
            
            //执行请求
            if (self.forbidLocalHandler) {
                
                self.forbidLocalHandler();
            }
        }
            break;
        default:
            break;
    }
}

@end



@implementation QDLocationManager (XNDlocation)

+(BOOL)hasLocationStatus
{
    return ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedAlways || [CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedWhenInUse);
}

+(NSDictionary *)localInfo
{
    return [[NSUserDefaults standardUserDefaults] valueForKey:QDLocationManagerDefaultsAddressKey];
}


+(NSString *)province
{
    
    NSString *province = [self.localInfo valueForKey:@"province"];
    
    if (province && [province hasSuffix:@"省"]) {
        
        province = [province substringToIndex:province.length - 1];
    }
    
    return province;
    
}


+(NSString *)city
{
    NSString *city = [self.localInfo valueForKey:@"city"];
    if (city && [city hasSuffix:@"市"]) {
        city = [city substringToIndex:city.length -1];
    }
    return city;
}


+(NSString *)street
{
    return [self.localInfo valueForKey:@"street"];
}


+(NSString *)subLocality
{
    return [self.localInfo valueForKey:@"subLocality"];
}


+(NSString *)name
{
    return [self.localInfo valueForKey:@"name"];
}


+(NSString *)thoroughfare
{
    return [self.localInfo valueForKey:@"thoroughfare"];
}


+(NSNumber *)longitude
{
    NSNumber *longtude = [[NSUserDefaults standardUserDefaults]valueForKey:QDLocationManagerLongitudeKey];
    
    return longtude ? longtude : @(120.409693);
}


+(NSNumber *)latitude
{
    NSNumber *latitude = [[NSUserDefaults standardUserDefaults]valueForKey:QDLocationManagerLatitudeKey];
    
    return latitude ? latitude : @(36.131241);
}


@end
